<template>
	<el-card class="box-card">
		<el-form ref="queryForm" :model="query" :inline="true">
			<el-form-item label="菜单名称" prop="name">
				<el-input v-model="query.name" placeholder="请输入菜单名称" clearable @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb20">
			<el-col :span="1.5">
				<el-button v-hasPermi="['/menu/addMenu']" type="primary" icon="el-icon-plus" @click="handleAdd()">新增</el-button>
			</el-col>
		</el-row>

		<el-card class="box-card">
			<el-table
        v-loading="listLoading"
        :data="dataList"
        border
        row-key="id"
        :tree-props="{children: 'children'}"
      >
				<el-table-column prop="name" label="菜单名称" show-overflow-tooltip width="320">
					<template slot-scope="{row}">
            <span :style="{'padding-left': row.children&&!row.children.length&&row.parentId===0 ? '24px':0}">{{row.name}}</span>
					</template>
        </el-table-column>
				<el-table-column label="icon图标" align="center" prop="icon" width="100px">
					<template slot-scope="{row}">
						<i style="font-size:18px;" :class="[`el-icon-${row.icon}`]"></i>
					</template>
				</el-table-column>
				<el-table-column prop="sort" label="排序" align="center" width="120" />
				<el-table-column label="菜单类型" align="center" prop="level">
					<template slot-scope="{row}">
						<span v-if="row.level===1">目录</span>
						<span v-else>菜单</span>
					</template>
				</el-table-column>
				<el-table-column label="创建时间" align="center" prop="ctime">
					<template slot-scope="{row}">
						<span>{{ row.ctime | parseTime }}</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
					<template slot-scope="{row}">
						<el-button v-hasPermi="['/menu/addMenu']" v-if="row.level!==2" type="text" @click="handleAdd(row)">新增菜单</el-button>
						<el-button v-hasPermi="['/menu/updateMenu']" type="text" @click="handleUpdate(row)">编辑</el-button>
						<el-button v-hasPermi="['/menu/delete/*']" type="text" @click="handleDelete(row.id)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
    </el-card>

		<!-- 添加或修改菜单 -->
		<el-dialog :title="(formModel.id?'编辑':'新增')+'菜单'" :visible.sync="formVisible" width="600px" append-to-body>
			<el-form ref="formModel" :model="formModel" :rules="formRules" label-width="80px">
				<el-row>
					<el-col :span="24" v-if="formModel.parentId!==0">
						<el-form-item label="上级目录">
							<span>{{formModel.parentName}}</span>
						</el-form-item>
					</el-col>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="level">
              <el-radio-group v-model="formModel.level">
                <el-radio-button :disabled="formModel.parentId!==0" :label="1">目录</el-radio-button>
                <el-radio-button :label="2">菜单</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
					<el-col :span="12">
						<el-form-item label="菜单名称" prop="name">
							<el-input v-model="formModel.name" placeholder="请输入菜单名称" maxlength="10" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="显示排序" prop="sort">
              <el-input-number v-model="formModel.sort" controls-position="right" :min="0" />
						</el-form-item>
					</el-col>
					<el-col :span="24" v-if="formModel.level===2">
						<el-form-item label="菜单URL" prop="url">
							<el-input v-model="formModel.url" placeholder="请输入菜单URL" maxlength="100" />
						</el-form-item>
					</el-col>
          <el-col :span="24">
            <el-form-item label="菜单图标">
              <el-popover
                placement="bottom-start"
                width="460"
                trigger="click"
                @show="$refs['iconSelect'].reset()"
              >
                <IconSelect ref="iconSelect" @selected="selected" />
                <el-input class="icon-input" slot="reference" v-model="formModel.icon" placeholder="点击选择图标" clearable>
                  <i slot="prefix" style="font-size: 18px;" :class="[`el-icon-${formModel.icon}`]" />
                </el-input>
              </el-popover>
            </el-form-item>
          </el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="formVisible=!formVisible;reset;">取 消</el-button>
				<el-button :loading="submitLoading" type="primary" @click="submitForm">确 定</el-button>
			</div>
		</el-dialog>
	</el-card>
</template>

<script>
import { listMenus, addMenu, updateMenu, menuDeleteId } from '@/api/system/menu'
import IconSelect from "@/components/IconSelect";

export default {
  components: { IconSelect },
  data () {
    return {
      // 列表数据
      query: {},
      dataList: [],
      listLoading: false,
      // 新增/编辑用户
      formVisible: false,
      submitLoading: false,
      formModel: {
        parentId: 0,
        level: 1,
        icon: '',
        sort: 0
      },
      formRules: {
        name: [
          { required: true, message: "菜单名称不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "排序字段不能为空", trigger: "blur" }
        ],
        url: [
          { required: true, message: "菜单URL不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created () {
    this.handleQuery()
  },
  methods: {
    // 选择图标
    selected(name) {
      this.$set(this.formModel, 'icon', name)
    },
    handleQuery () {
      this.listLoading = true
      listMenus().then(res => {
        const { name } = this.query
        let arr = []
        if (name) {
          res.data.forEach(o => {
            if (o.name.indexOf(name) !== -1) {
              arr.push(o)
            } else {
              o.children = o.children.filter(m => m.name.indexOf(name) !== -1)
              !!o.children.length&&arr.push(o)
            }
          })
        } else {
          arr = res.data
        }
        this.dataList = arr
        this.listLoading = false
      }).catch(err => {
        if (err.code === -103) {
          this.$router.push('/403')
        }
        this.listLoading = false
      })
    },
    resetQuery () {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleAdd (row) {
      this.reset()
      this.formVisible = !this.formVisible
      if (row) {
        this.formModel = { ...this.formModel, level: 2, parentId: row.id, parentName: row.name }
      }
    },
    handleUpdate (row) {
      this.handleAdd()
      this.formModel = { ...row }
    },
    handleDelete (id) {
      this.$confirm(`请确认是否要删除该菜单?`, { type: 'warning' }).then(() => {
        menuDeleteId(id).then(() => {
          this.$message.success('删除成功')
          this.handleQuery()
        })
      })
    },
    // 新增/编辑
    submitForm () {
      this.submitLoading = true
      this.$refs["formModel"].validate(async valid => {
        if (valid) {
          try {
            if (this.formModel.id) {
              await updateMenu(this.formModel)
              this.$message.success('修改成功')
            } else {
              await addMenu(this.formModel)
              this.$message.success('新增成功')
            }
            this.formVisible = !this.formVisible
            this.handleQuery()
            this.submitLoading = false
          } catch (error) {
            this.submitLoading = false
          }
        } else {
          this.submitLoading = false
        }
      })
    },
    // 表单重置
    reset () {
      this.formModel = {
        parentId: 0,
        level: 1,
        icon: '',
        sort: 0
      }
      this.resetForm("formModel")
    }
  }
}
</script>

<style lang="scss">
.icon-input {
  .el-input__prefix{
    height: 32px;
    left: 6px;
    display: flex;
    align-items: center;
  }
}
</style>
